//app.js
App({
  onLaunch: function () { 
    wx.clearStorage()
    this.login()
  },
  login(callback){
    // 获取用户信息
    const that = this
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          that.globalData.isSetininfo = false
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
              wx.login({
                success: resd => {
                  const code = resd.code
                  wx.getUserInfo({
                    success: res => {
                      that.globalData.userInfo = res.userInfo
                      // 登录
                      let encodes = res.encryptedData;
                      let iv = res.iv;
                      wx.request({
                        url: that.globalData.damain+'Login/onLogin',
                        header: { 'content-type': 'application/x-www-form-urlencoded' },
                        method: 'POST',
                        dataType: 'json',
                        data: {
                          jscode: code,
                          encryptedData: encodes,
                          iv: iv
                        },
                        success: (res) => {
                          if (res.data.code == 1) {
                            that.globalData.session_id = res.data.data.session_id
                          } else {
                            wx.showToast({
                              title: '登录失败!',
                              icon: 'none'
                            })
                          }
                          if (callback) {
                            callback(res.data.data.session_id)
                          }
                        }
                      })
                      }
                      })
                }
              })
        }
      }
    })
  },
  http(params,apiurl) {
    const {session_id} = this.globalData
    return new Promise((resolve, reject) => {
      wx.request({
        method: 'POST',
        url: apiurl,
        dataType: 'json',
        data: {
          ...params
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: (res) => {
          res.data.code >= 0 && resolve(res.data) 
        },
        fail: err => {
          reject(err)
        }
      })
    })
  },

  globalData: {
    userInfo: null,
    session_id: '', 
    isSetininfo: true,
    damain: '',
  }
})